using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utils.Misc;

namespace Utils.Text
{
    public class LightString
    {
        static readonly char[] numbers = new char[] {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
        };

        StringBuilder builder;

        public StringBuilder StringBuilder { get { return builder; } }

        public LightString(int capacity)
        {
            builder = new StringBuilder(capacity, capacity);
        }

        public void Clear()
        {
            builder.Remove(0, builder.Length);
        }

        public LightString Set(string value)
        {
            Clear();
            Append(value);
            return this;
        }

        public LightString Set(byte value)
        {
            Clear();
            Append(value);
            return this;
        }

        public LightString Set(int value)
        {
            Clear();
            Append(value);
            return this;
        }

        public LightString Set(long value)
        {
            Clear();
            Append(value);
            return this;
        }

        public LightString Set(float value)
        {
            Clear();
            Append(value);
            return this;
        }

        public LightString Set(float value, int decimalPlaces)
        {
            Clear();
            Append(value, decimalPlaces);
            return this;
        }

        public LightString Set(double value, int decimalPlaces)
        {
            Clear();
            Append(value, decimalPlaces);
            return this;
        }

        public LightString Set(double value)
        {
            Clear();
            Append(value);
            return this;
        }

        public LightString Append(string value)
        {
            if (value != null)
            {
                if (builder.Capacity - builder.Length >= value.Length)
                {
                    builder.Append(value);
                }
                else if (builder.Capacity - builder.Length > 0)
                {

                }
            }
            return this;
        }

        public LightString Append(byte value)
        {
            recursiveAppend(value);
            return this;
        }

        public LightString Append(int value)
        {
            if (value < 0)
            {
                Append('-');
                recursiveAppend(-value);
            }
            else
            {
                recursiveAppend(value);
            }
            return this;
        }

        public LightString Append(long value)
        {
            if (value < 0)
            {
                Append('-');
                recursiveAppend(-value);
            }
            else
            {
                recursiveAppend(value);
            }
            return this;
        }

        public LightString Append(float value)
        {
            Append(value, int.MaxValue);
            return this;
        }

        /*
         * Uses an algorithm that covers the sane range of possible values but will
         * fail to render extreme values, NaNs and infinity. In these cases, false
         * is returned and the traditional double.ToString() method can be used.
         */
        public LightString Append(float value, int decimalPlaces)
        {
            const int ExponentBits = 0xFF; // Bit mask for the exponent bits
            const int FractionalBitCount = 23; // Number of bits for fractional part
            const int ExponentBias = 127; // Bias subtraced from exponent
            const int NumericBitCount = 31; // Bits without sign

            // You don't need modify these as they're calculated based on
            // the constants assigned above.
            const int FractionalBits = (2 << FractionalBitCount) - 1;
            const int HighestFractionalBit = (1 << FractionalBitCount);
            const int FractionalBitCountPlusOne = FractionalBitCount + 1;

            int intValue = FloatHelper.ReinterpretAsInt(value);
            int exponent = ((intValue >> FractionalBitCount) & ExponentBits) - ExponentBias;
            int mantissa = (intValue & FractionalBits) | HighestFractionalBit;

            int integral;
            int fractional;
            if (exponent >= 0)
            {
                if (exponent >= FractionalBitCount)
                {
                    if (exponent >= NumericBitCount)
                    {
                        return this;
                    }
                    integral = mantissa << (exponent - FractionalBitCount);
                    fractional = 0;
                }
                else
                {
                    integral = mantissa >> (FractionalBitCount - exponent);
                    fractional = (mantissa << (exponent + 1)) & FractionalBits;
                }
            }
            else
            {
                //if (exponent < -FractionalBitCount)
                //{
                //    return this;
                //}
                integral = 0;
                fractional = (mantissa & FractionalBits) >> -(exponent + 1);
            }

            // Build the integral part      
            if (intValue < 0)
            {
                Append('-');
            }
            if (integral == 0)
            {
                Append('0');
            }
            else
            {
                recursiveAppend(integral);
            }

            if (decimalPlaces > 0)
            {
                Append('.');

                // Build the fractional part
                if (fractional == 0)
                {
                    Append('0');
                }
                else
                {
                    while (fractional != 0)
                    {
                        fractional *= 10;
                        int digit = (fractional >> FractionalBitCountPlusOne);
                        Append(numbers[digit]);
                        fractional &= FractionalBits;

                        --decimalPlaces;
                        if (decimalPlaces == 0)
                        {
                            break;
                        }
                    }
                }
            }

            return this;
        }

        public LightString Append(double value)
        {
            Append(value, int.MaxValue);
            return this;
        }

        /*
         * an algorithm that covers the sane range of possible values but will
         * fail to render extreme values, NaNs and infinity. In these cases, false
         * is returned and the traditional double.ToString() method can be used.
         */
        public LightString Append(double value, int decimalPlaces)
        {
            const long ExponentBits = 0x7FF; // Bit mask for the exponent bits
            const int FractionalBitCount = 52; // Number of bits for fractional part
            const int ExponentBias = 1023; // Bias subtraced from exponent
            const int NumericBitCount = 63; // Bits without sign

            // You don't need modify these as they're calculated based on
            // the constants assigned above.
            const long FractionalBits = (2L << FractionalBitCount) - 1;
            const long HighestFractionalBit = (1L << FractionalBitCount);
            const int FractionalBitCountPlusOne = FractionalBitCount + 1;

            long longValue = FloatHelper.ReinterpretAsLong(value);
            long exponent = ((longValue >> FractionalBitCount) & ExponentBits) - ExponentBias;
            long mantissa = (longValue & FractionalBits) | HighestFractionalBit;

            long integral;
            long fractional;
            if (exponent >= 0)
            {
                if (exponent >= FractionalBitCount)
                {
                    if (exponent >= NumericBitCount)
                    {
                        return this;
                    }
                    integral = mantissa << (int)(exponent - FractionalBitCount);
                    fractional = 0;
                }
                else
                {
                    integral = mantissa >> (int)(FractionalBitCount - exponent);
                    fractional = (mantissa << (int)(exponent + 1)) & FractionalBits;
                }
            }
            else
            {
                if (exponent < -FractionalBitCount)
                {
                    return this;
                }
                integral = 0;
                fractional = (mantissa & FractionalBits) >> -(int)(exponent + 1);
            }

            // Build the integral part      
            if (longValue < 0)
            {
                Append('-');
            }
            if (integral == 0)
            {
                Append('0');
            }
            else
            {
                recursiveAppend(integral);
            }

            if (decimalPlaces > 0)
            {
                Append('.');

                // Build the fractional part
                if (fractional == 0)
                {
                    Append('0');
                }
                else
                {
                    while (fractional != 0)
                    {
                        fractional *= 10;
                        long digit = (fractional >> FractionalBitCountPlusOne);
                        Append(numbers[digit]);
                        fractional &= FractionalBits;

                        --decimalPlaces;
                        if (decimalPlaces == 0)
                        {
                            break;
                        }
                    }
                }
            }

            return this;
        }

        void Append(char value)
        {
            if (builder.Length < builder.Capacity)
            {
                builder.Append(value);
            }
        }

        private void recursiveAppend(int remaining)
        {
#if WINDOWS
            int digit;
            int tenth = Math.DivRem(remaining, 10, out digit);
#else
            int digit = remaining % 10;
            int tenth = remaining / 10;
#endif

            if (tenth > 0)
            {
                recursiveAppend(tenth);
            }

            Append(numbers[digit]);
        }

        private void recursiveAppend(long remaining)
        {
#if WINDOWS
            long digit;
            long tenth = Math.DivRem(remaining, 10, out digit);
#else
            long digit = remaining % 10;
            long tenth = remaining / 10;
#endif

            if (tenth > 0)
            {
                recursiveAppend(tenth);
            }

            Append(numbers[digit]);
        }
    }
}
